//
//  ExtensionSwift.swift
//  SwiftTest
//
//  Created by 齐凯 on 2019/2/14.
//  Copyright © 2019年 QiKai. All rights reserved.
//
// http://www.swift51.com/swift4.0/chapter2/21_Extensions.html
/*  扩展 相当于oc中的categoy
    扩展 就是为一个已有的类、结构体、枚举类型或者协议类型添加新功能
 
 Swift 中的扩展可以：
 添加计算型属性和计算型类型属性
 定义实例方法和类型方法
 提供新的构造器
 定义下标
 定义和使用新的嵌套类型
 使一个已有类型符合某个协议
 
 */
/*
 UIKit 框架提供了用于创建触摸界面的类
 
 所有 iOS 应用都基于 UIKit 框架，缺少了它你的应用将无法运行。UIKit 提供了绘制画面、处理事件和创建通用用户界面元素的基础架构。UIKit 还会管理要显示在屏幕上的内容从而对复杂的应用进行组织。
 
 UIKit 框架可以用来：
 
 创建并管理用户界面。
 处理触摸和动作事件。
 显示文字和网页内容。
 为多任务优化你的应用。
 创建自定义的用户界面元素。
 原文：https://blog.csdn.net/db906645344/article/details/44617941
 
 */
import UIKit

//MARK: UIColor

extension UIColor{
    //常用颜色
    //static let blackcolor = colorWith(hexString: <#T##String#>)
    
    
    //随机色
    class var randomColor: UIColor {
        get{
            let red = CGFloat(arc4random()%256)/255.0
            let green = CGFloat(arc4random()%256)/255.0
            let blue = CGFloat(arc4random()%256)/255.0
            return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        }
    }
    /// 传入一个16进制的字符串，返回该16进制代表的颜色（默认alpha位1）
    ///
    /// - Parameter hexString: 代表颜色的16进制字符串
    /// - Returns: 该16进制表示的颜色
    static func colorWith(hexString: String) -> UIColor {
        return UIColor.colorWith(hexString: hexString, alpha: 1.0)
    }
    
    /// 传入一个16进制的字符串，返回该16进制代表的颜色
    ///
    /// - Parameter hexString: 代表颜色的16进制字符串,支持@“#123456”、 @“0X123456”、 @“123456”三种格式
    ///   - alpha: 颜色的透明度
    /// - Returns: 该16进制表示的颜色
    
    static func colorWith(hexString: String, alpha: CGFloat) -> UIColor {
        //删除字符串中的空格
        var cString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
        // strip 0X if it appears
        //如果是0x开头的，那么截取字符串，字符串从索引为2的位置开始，一直到末尾
        if cString.hasPrefix("0X") {
            cString = ((cString as NSString).substring(from: 2) as NSString) as String
        }
        //如果是#开头的，那么截取字符串，字符串从索引为1的位置开始，一直到末尾
        if cString.hasPrefix("#") {
            cString = ((cString as NSString).substring(from: 1) as NSString) as String
        }
        // String should be 6 or 8 characters
        if cString.count < 6 {
            //print("colorWithHexString is wrong！")
            return UIColor.clear
        }
        // Separate into r, g, b substrings
        let rString = (cString as NSString).substring(to: 2)
        let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
        
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        
        return UIColor.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
    }
    
    
}
//MARK: UIView
extension UIView{
    //字体 字号
    func kFontSize(_ a: CGFloat) -> UIFont {
        return UIFont.systemFont(ofSize: a)
    }
    func kFontBoldSize(_ a: CGFloat) -> UIFont {
        return UIFont.boldSystemFont(ofSize: a)
    }
    /// 圆角
    ///
    /// - Parameters:
    ///   - borderWidth: 边框宽度
    ///   - borderColor: 边框颜色
    ///   - cornerRadius: 圆角半径
    func kSetBoderwidth(borderWidth: CGFloat?, borderColor: UIColor?, cornerRadius: CGFloat?) {
        layer.shouldRasterize = true
        layer.rasterizationScale = UIScreen.main.scale
        layer.masksToBounds = true
        layer.borderWidth = borderWidth!
        layer.borderColor = borderColor?.cgColor
        layer.cornerRadius = cornerRadius!
    }
}


extension UILabel{

}



extension UIButton{
    func kSetImage(str:String){
        self.setImage(UIImage(named: str), for: UIControl.State.normal)
        self.adjustsImageWhenHighlighted = false
    }
    func kSetBackImage(str:String){
        self.setBackgroundImage(UIImage(named:str), for: UIControl.State.normal)
        self.adjustsImageWhenHighlighted = false
    }
    func kSetSelectImage(str:String){
        self.setImage(UIImage(named: str), for: UIControl.State.selected)
        self.adjustsImageWhenHighlighted = false
    }
    func kSetSelectBackImage(str:String){
        self.setBackgroundImage(UIImage(named:str), for: UIControl.State.selected)
        self.adjustsImageWhenHighlighted = false
    }
    
    /// 快速创建按钮(全)
    ///
    /// - Parameters:
    ///   - imageName: 图片
    ///   - titleColor: 字体颜色
    ///   - titleFont: 字体大小
    ///   - backgroundColor: 背景颜色
    ///   - title: 标题
    /// - Returns: button
    static func kButtonWithAll(imageName: String?, titleColor: UIColor?, titleFont: UIFont?, backgroundColor: UIColor?, title: String?) -> UIButton {
        let button = UIButton(type: .custom)
        if backgroundColor != nil{
             button.backgroundColor = backgroundColor
        }
        if title?.count != nil {
            button.setTitle(title, for: UIControl.State.normal)
        }
        if titleColor != nil {
            button.setTitleColor(titleColor, for: UIControl.State.normal)
        }
        if titleFont != nil {
            button.titleLabel?.font = titleFont
        }
        if (imageName?.count) != nil {
            button.setImage(UIImage(named: imageName!), for: UIControl.State.normal)
            if title?.count != nil {
//                button.imageEdgeInsets = UIEdgeInsets(top: 0, left: UIScreen.main.bounds.size.width / 375, bottom: 0, right: 0)
//                button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: UIScreen.main.bounds.size.width / 375)
                button.imageEdgeInsets = UIEdgeInsets(top: 0, left: UIScreen.main.bounds.size.width / 375, bottom: 0, right: 0)
                button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: UIScreen.main.bounds.size.width / 375)

            }
        }
        return button
    }
  


}
extension UIButton {
    // 实现button文字图片 上下左右布局 .
    // 用的时候，一定要在布局完之后
    @objc func kSetImageAndTitle(image anImage: UIImage?, title: String,
                   titlePosition: UIView.ContentMode, additionalSpacing: CGFloat, state: UIControl.State){
        self.imageView?.contentMode = .center
        self.setImage(anImage, for: state)
        positionLabelRespectToImage(title: title, position: titlePosition, spacing: additionalSpacing)
        
        self.titleLabel?.contentMode = .center
        self.setTitle(title, for: state)
    }
    
    private func positionLabelRespectToImage(title: String, position: UIView.ContentMode,
                                             spacing: CGFloat) {
        let imageSize = self.imageRect(forContentRect: self.frame)
        let titleFont = self.titleLabel?.font!
        let titleSize = title.size(withAttributes: [NSAttributedString.Key.font: titleFont!])
        
        var titleInsets: UIEdgeInsets
        var imageInsets: UIEdgeInsets
        
        switch (position){
        case .top:
            titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing),
                                       left: -(imageSize.width), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
        case .bottom:
            titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing),
                                       left: -(imageSize.width), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
        case .left:
            titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0,
                                       right: -(titleSize.width * 2 + spacing))
        case .right:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        default:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
        
        self.titleEdgeInsets = titleInsets
        self.imageEdgeInsets = imageInsets
    }
}
extension UIViewController{
    // 通知
    public func addNotificationObserver(name: Notification.Name, selector: Selector) {
        NotificationCenter.default.addObserver(self, selector: selector, name: name, object: nil)
    }
    
    public func removeNotificationObserver(name: Notification.Name) {
        NotificationCenter.default.removeObserver(self, name: name, object: nil)
    }
    
    public func removeNotificationsObserver() {
        NotificationCenter.default.removeObserver(self)
    }
    
    func kAlter(title:String?,message:String?,cancleBlock:@escaping (()->()),sureBlock:@escaping (()->Void))  {
        let alterController = UIAlertController.init(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
        let actionCancle = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel) { (UIAlertAction) in
            cancleBlock()
        }
        let actionSure = UIAlertAction.init(title: "确定", style: UIAlertAction.Style.default) { (UIAlertAction) in
            sureBlock()
        }
        alterController.addAction(actionCancle)
        alterController.addAction(actionSure)
        self.present(alterController, animated: true, completion: nil)
        
    }
}

extension UIScrollView{
    
}








